import React, {FormEvent, useEffect, useState} from "react";
import {uploadImage} from "../../http/imageApi";
import AddTokenDto from "../../utils/dto/token/addTokenDto";
import {addToken} from "../../http/tokenApi";
import {getChains} from "../../http/chainApi";
import Chain from "../../models/Chain";
import {useNavigate} from "react-router-dom";
import routeNames from "../../utils/routeNames";

const IgoApplyPage = () => {
    const [projectName, setProjectName] = useState("");
    const [projectSymbol, setProjectSymbol] = useState("");
    const [projectBrief, setProjectBrief] = useState("");
    const [chainId, setChainId] = useState("");
    const [targetRaise, setTargetRaise] = useState(0);
    const [tokenPrice, setTokenPrice] = useState(0);
    const [tokenImage, setTokenImage] = useState<File | null>(null);
    const [chains, setChains] = useState<Chain[]>([]);
    const navigate = useNavigate()

    useEffect(() => {
        getChains().then(response => {
            if (response.status === 200)
                setChains(response.data.chains)
            else
                alert(response.statusText)
        })
    }, []);

    const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        if (tokenImage) {
            uploadImage(tokenImage).then(response => {
                if (response.status !== 200) {
                    console.log(response.statusText);
                } else {
                    let dto = new AddTokenDto(projectName, tokenPrice, projectSymbol, chainId, targetRaise, projectBrief, response.data.imageId)
                    addToken(dto).then(response => {
                            if (response.status === 200) {
                                alert('Токен успешно создан')
                                navigate(routeNames.HOME_PAGE)
                            } else
                                alert(response.statusText)
                        }
                    )
                }
            })
        } else {
            let dto = new AddTokenDto(projectName, tokenPrice, projectSymbol, chainId, targetRaise, projectBrief, null)
            addToken(dto).then(response => {
                    if (response.status === 200) {
                        alert('Токен успешно создан')
                    } else
                        alert(response.statusText)
                }
            )
        }
    }
    
    return (
        <>
            <div className="gamfi-breadcrumbs-section">
                <div className="container">
                    <div className="apply-heading text-center">
                        <h2 className="mb-0">Apply for IGO</h2>
                    </div>
                </div>
            </div>
            <div className="apply-section pt-65 md-pt-45 pb-120 md-pb-80">
                <div className="container">
                    <div className="row justify-content-center">
                        <div className="col-lg-6 col-md-8">
                            <div className="apply-form">
                                <form onSubmit={handleSubmit}>
                                    <div className="input__group input__group--v2 mb-23">
                                        <label>Project Name</label>
                                        <input
                                            type="text"
                                            name="project"
                                            id="project"
                                            placeholder="Enter the name of your project"
                                            value={projectName}
                                            onChange={(e) => setProjectName(e.target.value)}
                                            required
                                        />
                                    </div>
                                    <div className="input__group input__group--v2 mb-23">
                                        <label>Project Symbol</label>
                                        <input
                                            type="text"
                                            name="projectSymbol"
                                            id="projectSymbol"
                                            placeholder="Enter the symbol of your project"
                                            value={projectSymbol}
                                            onChange={(e) => setProjectSymbol(e.target.value)}
                                            minLength={3}
                                            maxLength={3}
                                            required
                                        />
                                    </div>
                                    <div className="input__group input__group--v2 mb-23">
                                        <label>Project Brief</label>
                                        <textarea
                                            name="project-brief"
                                            id="project-brief"
                                            cols={30}
                                            rows={3}
                                            placeholder="Tell us about the project you want to launch"
                                            value={projectBrief}
                                            onChange={(e) => setProjectBrief(e.target.value)}
                                            required
                                        ></textarea>
                                    </div>
                                    <div className="radio-button">
                                        <h5 className="mt-35">Blockchain/Platform</h5>
                                        <select
                                            onChange={(e) => setChainId(e.target.value)} required>
                                            <option value="">Select blockchain</option>
                                            {chains.filter(c => !c.name.includes("All Block Chain")).sort((a, b) => a.name.localeCompare(b.name)).map(chain => (
                                                <option key={chain.id}
                                                        value={chain.id}>{chain.name}</option>
                                            ))}
                                        </select>
                                    </div>
                                    <div className="input__group input__group--v2 mt-23 mb-23">
                                        <label>Target Raise</label>
                                        <input
                                            type="number"
                                            name="target-raise"
                                            id="target-raise"
                                            placeholder="How much are you planning on raising on the IGO?"
                                            value={targetRaise}
                                            onChange={(e) => setTargetRaise(Number.parseInt(e.target.value))}
                                            required
                                        />
                                    </div>
                                    <div className="input__group input__group--v2 mt-23 mb-23">
                                        <label>Token Price</label>
                                        <input
                                            type="number"
                                            name="token-price"
                                            id="token-price"
                                            placeholder="How much are you planning on selling 1 token"
                                            value={tokenPrice}
                                            onChange={(e) => setTokenPrice(Number.parseInt(e.target.value))}
                                            required
                                        />
                                    </div>
                                    <div className="input__group input__group--v2 mt-23 mb-23">
                                        <label>Image:</label>
                                        <input
                                            type="file"
                                            onChange={(e) => {
                                                if (e.target.files !== null) {
                                                    const file = e.target.files[0];
                                                    setTokenImage(file);
                                                }
                                            }}
                                        />
                                    </div>
                                    <div className="input__group mt-40">
                                        <button className="theme-btn blue w-100" type="submit">
                                            <span>Submit IGO Project</span>
                                            <span className="hover-shape1"></span>
                                            <span className="hover-shape2"></span>
                                            <span className="hover-shape3"></span>
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </>
    )
}

export default IgoApplyPage;
